import React, { useEffect, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import axios from 'axios';
import LoadingScreen from './LoadingScreen';

const ProtectedRoute = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const location = useLocation();

  useEffect(() => {
    // 检查是否有token
    const checkAuth = async () => {
      const token = localStorage.getItem('token');
      
      if (!token) {
        setIsAuthenticated(false);
        setIsLoading(false);
        return;
      }
      
      try {
        // 验证token是否有效
        // 判断token是否已经包含"Bearer "前缀
        const tokenValue = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
        
        console.log('验证token:', tokenValue);
        
        const response = await axios.get('http://localhost:3001/lxt/verify-token', {
          headers: {
            'Authorization': tokenValue
          }
        });
        
        console.log('Token验证成功:', response.data);
        setIsAuthenticated(true);
      } catch (error) {
        // token无效或过期
        console.error('Token验证失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
        }
        localStorage.removeItem('token'); // 清除无效token
        setIsAuthenticated(false);
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, []);

  // 加载状态
  if (isLoading) {
    return <LoadingScreen message="验证登录状态..." />;
  }

  // 未认证，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 已认证，渲染子组件
  return children;
};

export default ProtectedRoute; 